import React from "react";
import { toJS } from "mobx";
import RelatedCard from "./RelatedCard";
import { Popover, Dropdown, Menu, Icon } from "antd";
import { DropTarget, DragSource } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import { dndTypes, dndTargets } from "../../../../constants";
import {WeaLocaleProvider} from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

const { TABLE, JOINED_TABLE } = dndTypes;

const spec = {
    beginDrag: (props) => ({ node: props.node }),
    endDrag: (props, monitor) => {
        const didDrop = monitor.didDrop();
        const node = monitor.getItem().node;

        props.onRemove(node, didDrop);
    }
};
const collect = (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    getItem: monitor.getItem(),
});
const targetSpec = {
    drop: (props, monitor) => {
        const target = props.node;
        const source = monitor.getItem().node;

        props.onDrop(source, target, dndTargets.TREE);
    }
};
const targetCollect = (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
});

@DropTarget([TABLE, JOINED_TABLE], targetSpec, targetCollect)
@DragSource(JOINED_TABLE, spec, collect)
export default class TreeNode extends React.Component {
    constructor(props) {
        super();
        this.state = {
            doc: document,
            relVisible: false,
            selected: props.node.selected
        };
    }

    componentDidMount() {
        const { connectDragPreview } = this.props

        if (connectDragPreview) {
            connectDragPreview(getEmptyImage(), {
                captureDraggingState: true,
            });
        }
        /*  setTimeout(() => {
             this.setState({
                 relVisible: node.relVisible
             });
         }, 200); */
    }

    getContent() {
        const { node, onRelatedFieldsChange, onJoinTypeChange } = this.props;

        return (
            this.state.relVisible ? <RelatedCard
                node={node}
                onJoinTypeChange={onJoinTypeChange}
                onRelatedFieldsChange={onRelatedFieldsChange}
            /> : null
        );
    }

    getRelatedFieldsLength(node) {
        const fields = toJS(node.relatedFields) || [];

        return fields.filter(f => f[0] && f[1]).length;
    }

    getMenu() {
        return (
            <Menu onClick={({ key }) => this.onMenuAction(key)}>
                <Menu.Item key='del'>{getLabel(502286,'删除')}</Menu.Item>
            </Menu>
        );
    }

    onMenuAction(actName) {
        const { onRemove, node } = this.props;

        switch (actName) {
            case 'del':
                onRemove(node);
                break;
            default:
                break;
        }
    }

    onSelectedToggle() {
        const { selected } = this.state;

        this.setState({ selected: !selected });
    }

    onPopoverVisible(relVisible) {
        this.setState({ relVisible });
    }

    render() {
        const {
            node, isOver, key, onOptClick,
            connectDragSource, connectDropTarget,
        } = this.props;
        const { relVisible, selected, doc } = this.state;
        const len = this.getRelatedFieldsLength(node);
        return (
            <div className='edc-ds-tree-box' key={key} ref={ref => this.container = ref}>
                <div className={`edc-ds-tree-item edc-ds-active ${selected ? 'selected' : ''} ${isOver ? 'on' : ''}`}>
                    {connectDropTarget(connectDragSource(
                        <h6 onClick={this.onSelectedToggle.bind(this)}>{node.text || node.name}</h6>
                    ))}
                    <Dropdown overlay={this.getMenu()} trigger={['click']} getDocument={() => window.document}>
                        <Icon type='down' />
                    </Dropdown>
                    <Popover
                        trigger="click"
                        placement="bottom"
                        content={this.getContent()}
                        visible={relVisible}
                        overlayClassName='edc-ds-popover'
                        getDocument={() => doc}
                        onVisibleChange={this.onPopoverVisible.bind(this)}
                        title={<div>{getLabel('502703','关联')}<Icon onClick={() => this.onPopoverVisible(false)} type='cross' /></div>}
                    >
                        <span className={`edc-ds-tree-opt ${!len ? 'err' : ''}`} onClick={() => onOptClick(node)}>
                            {len ? <b>{len}</b> : <Icon type='plus' />}
                            <Icon type='edit' />
                        </span>
                    </Popover>
                </div>
                <div className='edc-ds-tree-wrap'>
                    {this.props.children}
                </div>
            </div>
        );
    }
}